module nade.sprite;

import derelict.opengl.gl;

import nade.vector;
import nade.texture;


class Sprite {
	this(string path, uint frameCount = 1, uint skinCount = 1)
	{
		_texture = Texture.load(path);
		_tx = Texture._tx;
		_ty = Texture._ty;

		glBindTexture(GL_TEXTURE_2D, _texture);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

		_frameCount = frameCount;
		_skinCount = skinCount;
	}
	this(string path, string maskPath, uint frameCount = 1, uint skinCount = 1)
	{
		_texture = Texture.load(path, maskPath);
		_tx = Texture._tx;
		_ty = Texture._ty;

		_frameCount = frameCount;
		_skinCount = skinCount;
	}

	void render(const Vector2 size, int frame = 0, int skin = 0)
	{
		assert(frame >= 0  &&  frame < _frameCount);

		const from = -size*0.5;
		const to = size*0.5;

		const tx1 = _tx*skin*1.0/_skinCount;
		const tx2 = _tx*(skin + 1)*1.0/_skinCount;
		const ty1 = _ty*frame*1.0/_frameCount;
		const ty2 = _ty*(frame + 1)*1.0/_frameCount;

		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, _texture);

		glColor3f(1, 1, 1);
		glNormal3f(0, 0, 1);
		glBegin(GL_QUADS);
		glTexCoord2f(tx1, ty1); glVertex2f(from.x, from.y);
		glTexCoord2f(tx2, ty1); glVertex2f(to.x, from.y);
		glTexCoord2f(tx2, ty2); glVertex2f(to.x, to.y);
		glTexCoord2f(tx1, ty2); glVertex2f(from.x, to.y);
		glEnd();

		glDisable(GL_TEXTURE_2D);
	}

	uint frameCount() { return _frameCount; }

	private {
		GLuint		_texture;
		real		_tx, _ty;
		uint		_frameCount;
		uint		_skinCount;
	}
}
